package com.xxx.datalake.service;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * @ Author: Aneve
 * @ Project: datalake
 * @ Since: 2022/9/20 18:48
 * @ Description:
 */
public class GetMySqlResourcesData {

    public Map getMySqlTables(Connection connection) throws SQLException {
        HashMap<String, Object> tableNameMap = new HashMap<>();
        //获取元数据
        DatabaseMetaData metaData = (DatabaseMetaData) connection.getMetaData();
        //获得表信息
        ResultSet tables = metaData.getTables(null, null, null, new String[]{"TABLE"});
        //循环装入map中
        while (tables.next()){
            //保存字段名
            HashMap<String, String> columnNameMap = new HashMap<>();
            //获得表名
            String table_name = tables.getString("TABLE_NAME");

            //通过表名获得所有字段名
            ResultSet columns = metaData.getColumns(null, null, table_name, "%");
            //获得所有字段名
            while (columns.next()){
                //获得字段名
                String column_name = columns.getString("COLUMN_NAME");
                String type_name = columns.getString("TYPE_NAME");
                columnNameMap.put(column_name,type_name);
            }
            tableNameMap.put(table_name,columnNameMap);
        }
        return tableNameMap;
    }

    public String getPrimaryKey(Connection connection,String tableName) throws SQLException {
        DatabaseMetaData metaData = connection.getMetaData();
        //通过表名获得表的主键
        ResultSet primaryKeys = metaData.getPrimaryKeys(null, null, tableName);
        String primaryKeysName = null;
        //获得主键字段名
        while (primaryKeys.next()){
            primaryKeysName = primaryKeys.getString("COLUMN_NAME");
        }
        return primaryKeysName;
    }
}
